﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Collections;
using OnlineVideos.Entities;
using OnlineVideos.Data;
using System.Xml.Linq;
using Common.Library;
using System.Reflection;
using InsertIntoDataBase;
using HtmlAgilityPack;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using OnlineVideos.ViewModels;
using System.Threading.Tasks;

namespace OnlineVideos.Views
{
    public class Extraparam
    {
        public string Title
        {
            get;
            set;
        }
        public string TileDesc
        {
            get;
            set;
        }
        public string ImageUrl
        {
            get;
            set;
        }
        public Visibility Control
        {
            get;
            set;
        }
        public int Id
        {
            get;
            set;
        }
    }
    public class DownloadBlogInfo
    {

        public ShowList show
        {
            get;
            set;
        }
        public WebInformation web
        {
            get;
            set;
        }
        public Extraparam extra
        {
            get;
            set;
        }
        public ShowCategories sc
        {
            get;
            set;
        }
        public CategoriesByShowID cbs
        {
            get;
            set;
        }
       
    }
    public partial class OnlineShare : PhoneApplicationPage
    {
        int count = 10;
        public string CatName = string.Empty;
        public bool sortDate = false;
        public ObservableCollection<DownloadBlogInfo> DownloadList = default(ObservableCollection<DownloadBlogInfo>);
        public int startIndex = 1;
        public int maxresults = 10;
        public List<int> ListId = new List<int>();
        public OnlineShare()
        {
            InitializeComponent();
            Loaded += OnlineShare_Loaded;
        }

        void OnlineShare_Loaded(object sender, RoutedEventArgs e)
        {
           List<string> CatList = new List<string>();
           CatList.Add("Select Category");
            
            foreach(string cat in Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().ToListAsync()).Result.Select(i => i.BlogCategory).ToList())
            {
                CatList.Add(cat);
            }
            CategoryList.ItemsSource = CatList;
            TbSearch.Text = string.Empty;
            sortDate = false;
            DownloadList = new ObservableCollection<DownloadBlogInfo>();
            OnlineList.ItemsSource = DownloadList;
            CategoryList.SelectionChanged += CategoryList_SelectionChanged_1;
            CategoryList.SelectedIndex = 0;
            startIndex = 1;
            maxresults = 10;
           
                CatName = "Personal Finance";

                BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == "Personal Finance").FirstOrDefaultAsync()).Result;
                if (bt != null)
                {
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                }
        }
        public void loaddata(string url)
        {
            string feed = string.Empty;
            WebClient wclient = new WebClient();
            wclient.OpenReadCompleted += (sender1, e1) =>
            {
                if (e1.Error != null)
                    return;
                int BindId = 0;
                Stream str = e1.Result;
                XmlReader response = XmlReader.Create(str);
                SyndicationFeed feeds = SyndicationFeed.Load(response);
                string[] stringSeparators = new string[] { "??" };
                if (feeds.Items.Count() > 0)
                {
                    foreach (SyndicationItem f in feeds.Items)
                    {
                        bool exists = false;
                        foreach (SyndicationCategory sc in f.Categories)
                        {
                            if (sc.Name == "hide")
                            {
                                exists = true;
                            }
                        }
                      
                        if (exists == false)
                        {
                            int index = 0;
                            string[] xml = new string[2];
                            DownloadBlogInfo db = new DownloadBlogInfo();
                            db.extra = new Extraparam();
                            feed = HttpUtility.HtmlDecode(Regex.Replace(f.Summary.Text, "<[^>]+?>", ""));
                            HtmlDocument doc = new HtmlDocument();
                            doc.LoadHtml(f.Summary.Text);
                            foreach (HtmlNode node in doc.DocumentNode.SelectNodes(" //img"))
                            {
                                if (node.OuterHtml.Contains("src"))
                                {
                                    db.extra.ImageUrl = node.Attributes["src"].Value;
                                }
                            }
                            foreach (string stri in feed.Split(stringSeparators, StringSplitOptions.None))
                            {
                                xml[index] = stri;
                                index++;
                            }
                            BindId++;
                            db.extra.Id = BindId;
                            TextReader read = new StringReader(xml[1].ToString());
                            XDocument xdoc = XDocument.Load(read);
                          
                            var TablesList = Task.Run(async()=>await Constants.connection.Table<ShareTables>().ToListAsync()).Result.OrderBy(i => i.TableOrder).GroupBy(i => i.TableName);

                            foreach (var TableName in TablesList)
                            {
                                Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                                Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + TableName.Key.ToString());
                                object TableInstance = Activator.CreateInstance(TableType);
                                Convert.ChangeType(TableInstance, TableType, null);
                                var InsertType = typeof(InsertData<>);
                                Type[] Typeargs = { TableType };
                                var makeme = InsertType.MakeGenericType(Typeargs);
                                object InsertInstance = Activator.CreateInstance(makeme);
                                var Param = xdoc.Descendants("NewDataSet").Elements().Where(i => i.Name == TableName.Key.ToString()).FirstOrDefault();
                                if (Param != null)
                                {
                                    string propertyname = string.Empty;
                                    PropertyInfo[] ConditionProperty = db.GetType().GetProperties();
                                    foreach (PropertyInfo property in ConditionProperty)
                                    {
                                        if (property.PropertyType == TableType)
                                        {
                                            propertyname = property.Name;
                                            break;
                                        }
                                    }

                                    TableInstance = InsertInstance.GetType().GetMethod("XMLToEntity").Invoke(InsertInstance, new object[] { Param.ToString() });

                                    db.GetType().GetProperty(propertyname).SetValue(db, TableInstance, null);
                                }
                            }
                            db.extra.Control = Visibility.Visible;
                            db.extra.TileDesc = xml[0].ToString();
                            db.extra.Title = db.show.Title;
                            DownloadList.Add(db);
                        }
                        str.Close();
                       
                    }
                    if (DownloadList.Count() > 0)
                    {
                        notavailable.Visibility = Visibility.Collapsed;
                        DownloadBlogInfo db1 = new DownloadBlogInfo();
                        db1.extra = new Extraparam();
                        db1.extra.Title = "get more..";
                        db1.extra.Control = Visibility.Collapsed;
                        DownloadList.Add(db1);
                    }
                    else
                    {
                        notavailable.Visibility = Visibility.Visible;
                    }
                }
                else
                {
                   if( DownloadList.Count==0)
                    notavailable.Visibility = Visibility.Visible;
                    foreach (DownloadBlogInfo db in DownloadList)
                    {
                        if (db.extra.Title == "get more..")
                        {
                            DownloadList.Remove(db);
                        }
                    }
                }
                


            };

            wclient.OpenReadAsync(new Uri(url, UriKind.RelativeOrAbsolute));
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
           
                if (!string.IsNullOrEmpty(TbSearch.Text))
                {
                    SearchManager.SaveSearchHistory(TbSearch.Text);
                    startIndex = 1;
                    maxresults = 10;
                    sortDate = false;
                    DownloadList.Clear();
                   
                    BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&category=" + TbSearch.Text + "&alt=rss");
                }
          
            //http://www.blogger.com/feeds/blogID/posts/default?updated-min=2008-03-16T00:00:00&updated-max=2008-03-24T23:59:59&orderby=updated
        }

        private void sort_Click_1(object sender, EventArgs e)
        {
            startIndex = 1;
            maxresults = 10;
            sortDate = true;
            DownloadList.Clear();
            TbSearch.Text = string.Empty;
           
            BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
            loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&orderby=updated&alt=rss");
        }

        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            foreach (int id in ListId)
            {
                int catId=0;
                DownloadBlogInfo di = OnlineList.ItemsSource.Cast<DownloadBlogInfo>().Where(i => i.extra.Id == id).FirstOrDefault();
                WebClient wb = new WebClient();
                PropertyInfo[] ConditionProperty = di.GetType().GetProperties();
                
                    foreach (PropertyInfo property in ConditionProperty)
                    {
                        Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                        Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + property.PropertyType.Name.ToString());
                        if (TableType != null)
                        {

                        if (di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null) != null)
                        {
                            if (property.PropertyType.Name.ToString() == "ShowCategories")
                            {
                               string catname=di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryName").GetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null).ToString();
                                if (Task.Run(async()=>await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == catname).ToListAsync()).Result.Count > 0)
                                {
                                    catId = Task.Run(async()=>await Constants.connection.Table<ShowCategories>().Where(i => i.CategoryName == catname).FirstOrDefaultAsync()).Result.CategoryID;
                                    di.GetType().GetProperty(property.Name.ToString()).SetValue(di,new ShowCategories(), null);
                                }
                                else
                                {
                                    di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async()=>await Constants.connection.Table<ShowCategories>().FirstOrDefaultAsync()).Result != null) ? Task.Run(async()=>await Constants.connection.Table<ShowCategories>().ToListAsync()).Result.Max(i => i.CategoryID) + 1 : 1, null);
                                    catId = (int)di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CategoryID").GetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null);
                                }
                            }
                            else if (property.PropertyType.Name.ToString() == "CategoriesByShowID")
                            {
                               
                                di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CatageoryID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), catId, null);
                                di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null) ? di.show.ShowID : 1, null);
                            }
                            else
                            {

                               
                               
                                    if (property.PropertyType.Name.ToString() == "ShowList")
                                    {
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result != null) ? Task.Run(async()=>await Constants.connection.Table<ShowList>().ToListAsync()).Result.Max(i => i.ShowID) + 1 : 1, null);
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("TileImage").SetValue(di.show, di.show.ShowID.ToString() + ".jpg", null);
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("CreatedDate").SetValue(di.show, System.DateTime.Now, null);
                                    }
                                    else
                                    {
                                        di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null).GetType().GetProperty("ShowID").SetValue(di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), (Task.Run(async()=>await Constants.connection.Table<ShowList>().FirstOrDefaultAsync()).Result!= null) ? di.show.ShowID : 1, null);
                                    }
                                
                            }
                        }
                    }
                }
                wb.OpenReadCompleted += wb_OpenReadCompleted;
                wb.OpenReadAsync(new Uri(di.extra.ImageUrl, UriKind.RelativeOrAbsolute), di.show.ShowID.ToString() + ".jpg");
                SaveToDatabase(di);
              
                    History objHistory = new History();
                    objHistory.SaveMovieHistory(di.show.ShowID.ToString(), "");
               
            }
             NavigationService.GoBack();
        }

        void wb_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Result != null)
            {
               
                if (!Storage.DirectoryExists("/Images"))
                {
                    Storage.CreateDirectory("/Images");
                }
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var local = myIsolatedStorage.OpenFile("/" + Constants.ImagePath + e.UserState.ToString(), System.IO.FileMode.OpenOrCreate))
                    {
                        byte[] buffer = new byte[e.Result.Length / 4];
                        int bytesRead = -1;
                        e.Result.Position = 0;
                        while ((bytesRead = e.Result.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            local.Write(buffer, 0, bytesRead);
                        }

                        local.Close();
                        local.Dispose();
                        myIsolatedStorage.Dispose();
                    }
                }
            }
        }
        private void SaveToDatabase(DownloadBlogInfo di)
        {

            PropertyInfo[] ConditionProperty = di.GetType().GetProperties();
            foreach (PropertyInfo property in ConditionProperty)
            {
                Assembly DataAssembly = Assembly.Load(Constants.NamespaceForData);
                Type TableType = DataAssembly.GetType(Constants.NamespaceForData + "." + property.PropertyType.Name.ToString());
                if (TableType != null)
                {
                    object TableInstance = Activator.CreateInstance(TableType);

                    if (di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null) != null)
                    {
                        var InsertType = typeof(InsertData<>);
                        Type[] Typeargs = { TableType };
                        var makeme = InsertType.MakeGenericType(Typeargs);
                        object InsertInstance = Activator.CreateInstance(makeme);
                        InsertInstance.GetType().GetProperty("ParameterList").SetValue(InsertInstance, di.GetType().GetProperty(property.Name.ToString()).GetValue(di, null), null);
                        InsertInstance.GetType().GetMethod("Insert").Invoke(InsertInstance, null);
                    }
                }
            }
           
        }
        private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
        {
            if (!ListId.Contains((int)(sender as CheckBox).Tag))
                ListId.Add((int)(sender as CheckBox).Tag);
        }

        private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
        {
            if (ListId.Contains((int)(sender as CheckBox).Tag))
                ListId.Remove((int)(sender as CheckBox).Tag);
        }

       

       
        private void Tbtitle_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if ((sender as TextBlock).Text == "get more..")
            {
                foreach (DownloadBlogInfo db in DownloadList.ToList())
                {
                    if (db.extra.Title == "get more..")
                    {
                        DownloadList.Remove(db);
                    }
                }
               
                startIndex = count + 1;
                count = startIndex + 9;
                maxresults = 10;
                if (!string.IsNullOrEmpty(TbSearch.Text))
                {
                    
                    BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&category=" + TbSearch.Text + "&alt=rss");
                }
                else if (sortDate == true)
                {
                   
                    BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&orderby=updated&alt=rss");
                }
                else
                {
                   
                    BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                    loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                }
            }
        }

        private void CategoryList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
           
            if (CategoryList.ItemsSource != null && CategoryList.SelectedIndex!=0)
            {
                DownloadList.Clear();
                CatName = (sender as ListPicker).SelectedItem.ToString();
                startIndex = 1;
                maxresults = 10;
               
                BlogCategoryTable bt = Task.Run(async()=>await Constants.connection.Table<BlogCategoryTable>().Where(i => i.BlogCategory == CatName).FirstOrDefaultAsync()).Result;
                loaddata(bt.BlogUrl + "start-index=" + startIndex + "&max-results=" + maxresults + "&alt=rss");
                Loaded -= OnlineShare_Loaded;
                //CategoryList.SelectionChanged -= CategoryList_SelectionChanged_1;
            }
        }

        private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Text == "Select Category")
            {
                tb.Visibility = Visibility.Collapsed;
                tb.Loaded -= TextBlock_Loaded_1;
            }
        }

    }
}